package com.njtoyo.taxi.admin.task;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.njtoyo.taxi.admin.mapper.master.entity.Driver;
import com.njtoyo.taxi.admin.mapper.master.entity.DriverServiceLog;
import com.njtoyo.taxi.admin.mapper.master.entity.DriverServiceStatistics;
import com.njtoyo.taxi.admin.mapper.master.mapper.DriverMapper;
import com.njtoyo.taxi.admin.mapper.master.mapper.DriverServiceLogMapper;
import com.njtoyo.taxi.admin.service.data.DriverServiceStatisticsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Component
@Slf4j
public class DriverServiceLogTask {
    @Autowired
    private DriverServiceLogMapper driverServiceLogMapper;
    @Autowired
    private DriverServiceStatisticsService driverServiceStatisticsService;
    @Autowired
    private DriverMapper driverMapper;


    @Scheduled(cron = "0 0 5 * * ? ")
    public void driverServiceLog() {
        log.info("driverServiceLog start");
        Date taskTime = DateUtil.offsetDay(new Date(), -1);
        List<Driver> drivers = driverMapper.selectList(null);
        if (CollUtil.isNotEmpty(drivers)) {
            CollUtil.splitList(drivers, 20).forEach(driverList -> {
                List<Long> driverIds = driverList.stream().map(Driver::getId).collect(Collectors.toList());
                List<DriverServiceLog> driverServiceLogs = driverServiceLogMapper.selectListByTaskTimeGroupByDriverId(driverIds, DateUtil.beginOfDay(taskTime));
                if (CollUtil.isNotEmpty(driverServiceLogs)) {
                    List<DriverServiceStatistics> addlist = new ArrayList<>();
                    for (DriverServiceLog log : driverServiceLogs) {
                        DriverServiceStatistics driverServiceStatistic = new DriverServiceStatistics();
                        driverServiceStatistic.setDriverId(log.getDriverId());
                        driverServiceStatistic.setDuration(log.getDuration());
                        driverServiceStatistic.setCreatedAt(LocalDateTime.now());
                        driverServiceStatistic.setTaskTime(DateUtil.formatDate(taskTime));
                        addlist.add(driverServiceStatistic);
                    }
                    driverServiceStatisticsService.saveBatch(addlist);
                    addlist.clear();
                }
            });
        }
        log.info("driverServiceLog end");
    }
}
